package com.hjieli.config.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;


public class LoginFilter extends OncePerRequestFilter   {
	private static Logger logger = LoggerFactory.getLogger(LoginFilter.class);
	

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		ParameterRequestWrapper parameterRequestWrapper = new ParameterRequestWrapper(request);
		String requestUri = request.getRequestURI();
		logger.debug(requestUri);
		if(requestUri.contains("/admin/") || requestUri.contains("/api/")) {
			 Cookie[] cookies = request.getCookies();
			 if(cookies != null) {
				 for (Cookie cookie : cookies) {
					 if(cookie.getName().equals("x-token")) {
						 response.setHeader("Authorization", "bearer " + cookie.getValue());
						 parameterRequestWrapper.addParameter("access_token", cookie.getValue());
					 }
		         }
			 }
		}
		filterChain.doFilter(parameterRequestWrapper, response);
	}

	
}
